import json


from django.shortcuts import render
from django.views import View
from django.contrib.auth import login


from .models import Users
from . import forms
from utils.json_fun import to_json_data
from utils.res_code import Code, error_map


def login1(request):
    return render(request, 'users/login.html')


def register(request):
    return render(request, 'users/register.html')



class RegisterView(View):
    """
    user register
    /users/register/
    """
    def get(self, request):
        return render(request, 'users/register.html')


    def post(self, request):
        """
        
        :param request: 
        :return: 
        """
        #1、获取前端传来数据
        json_data = request.body
        if not json_data:
            return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR])

        dict_data = json.loads(json_data.decode('utf8'))

        #2、校验
        form = forms.RegisterForm(data=dict_data)
        if form.is_valid():

            # 3、保存数据
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            mobile = form.cleaned_data.get('mobile')
            user = Users.objects.create_user(username=username, password=password, mobile=mobile)

            #登入
            login(request, user)

            # 4、返回前端
            return to_json_data(errmsg="恭喜您，注册成功！")

        else:
            # 定义一个错误信息列表
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)


